﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using Common;
using System.Text.RegularExpressions;

namespace SYH.Utils
{
    public class FileUploadHelper
    {
        public static string thumbModel = "syh"; //缩略图生成模式

        public string md5_hash(string path)
        {
            try
            {
                FileStream get_file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] hash_byte = get_md5.ComputeHash(get_file);
                string resule = System.BitConverter.ToString(hash_byte);
                resule = resule.Replace("-", "");
                return resule;
            }
            catch (Exception e)
            {
                return e.ToString();

            }
        }

        /// <summary>
        /// 获取文件二进制内容的MD5校验码作为文件的名称
        /// </summary>
        /// <param name="stream">文件流</param>
        /// <returns>校验码</returns>
        public static string GetFileName(Stream stream)
        {
            try
            {
                System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] hash_byte = get_md5.ComputeHash(stream);
                string resule = System.BitConverter.ToString(hash_byte);
                resule = resule.Replace("-", "");
                return resule;
            }
            catch (Exception e)
            {
                return e.ToString();

            }
        }

        /// <summary>
        /// 获取图片上传路径
        /// </summary>
        /// <param name="serverPath">服务器地址</param>
        /// <param name="fileName">文件名</param>
        /// <param name="type">类型(临时文件,图片服务器文件)</param>
        /// <returns></returns>
        private static string GetUploadPath(string fileName,int albumid,int userid, int width, int height, string type)
        {
            string serverPath;

            if (width != 0)
            {
                fileName = fileName.Trim(System.IO.Path.GetExtension(fileName).ToCharArray()) + ".jpeg";
            }
            //文件名称的1-2位字符作为一级目录
            //string firstChars = fileName.Substring(0, 2);
            string firstChars = albumid.ToString(); 
            ///获取服务器路径
            Common.XmlHelper.SearchXml search = delegate(string value)
            {
                if (value == "all" || value.Contains(firstChars))
                    return true;
                else
                    return false;
            };

            if (type == "temp")
            {
                serverPath = HttpContext.Current.Server.MapPath(XmlHelper.Read(HttpContext.Current.Server.MapPath("~/App_Data/FileServerConfig.xml"), "/serverList/tempImage", "path"));
            }
            else
            {
                serverPath = XmlHelper.Read(HttpContext.Current.Server.MapPath("~/App_Data/FileServerConfig.xml"), "/serverList/server", search, "number", "path");
            }

            string thirdChars = fileName.Substring(1, 2);

            if (width > 0 && height > 0)
            {
                thirdChars = thirdChars + width.ToString() + height.ToString();
            }
            //string secondChars = fileName.Substring(3, 1);
            string secondChars = userid.ToString();
            string other = fileName.Substring(4, 5);
            //string thirdChars = (int.Parse(other, System.Globalization.NumberStyles.HexNumber) % 1024).ToString();
           
            string[] dirs = { serverPath.TrimEnd('\\'), firstChars, secondChars, thirdChars, fileName };
            return Path.Combine(dirs);
        }


        private static string GetUploadPath(string fileName, int albumid,int userid,int width, int height)
        {
            return GetUploadPath(fileName,albumid,userid, width, height, "");
        }

        private static string GetUploadWebUrl(string fileName, int width, int height, string type)
        {
            string serverPath;
            if (fileName.StartsWith("http://"))
            {
                return fileName;
            }
            if (string.IsNullOrEmpty(fileName) || !Regex.IsMatch(fileName, @"[0-9a-fA-F]{32,32}\.\w+"))
            {
                if (width == 100)
                {
                    return SYH.Config.ImageConfig.DefaultImageUrl("100x100");
                }
                else
                {
                    return SYH.Config.ImageConfig.DefaultImageUrl("310x310");
                }
            }



            if (width != 0)
            {
                fileName = fileName.Trim(System.IO.Path.GetExtension(fileName).ToCharArray()) + ".jpeg";

            }

            string firstChars = fileName.Substring(0, 2);
            ///获取服务器路径
            Common.XmlHelper.SearchXml search = delegate(string value)
            {
                if (value == "all" || value.Contains(firstChars))
                    return true;
                else
                    return false;
            };

            serverPath = XmlHelper.Read(HttpContext.Current.Server.MapPath("~/App_Data/FileServerConfig.xml"), "/serverList/server", search, "number", "webUrl");

            if (width > 0 && height > 0)
            {
                firstChars = firstChars + width.ToString() + height.ToString();
            }
            string secondChars = fileName.Substring(3, 1);
            string other = fileName.Substring(4, 5);
            string thirdChars = (int.Parse(other, System.Globalization.NumberStyles.HexNumber) % 1024).ToString();
            return serverPath.TrimEnd('/') + "/" + firstChars + "/" + secondChars + "/" + thirdChars + "/" + fileName;
        }


        /// <summary>
        /// 获取缩略图地址
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="thumbsize"></param>
        /// <returns></returns>
        public static string GetUploadWebUrl(string fileName, SYH.Enum.ThumbImageSize thumbsize)
        {
            int width; int height;
            GetSize(thumbsize, out width, out  height);
            return GetUploadWebUrl(fileName, width, height, "");
        }

        /// <summary>
        /// 获取原图访问路径
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetUploadWebUrl(string fileName)
        {
            return GetUploadWebUrl(fileName, 0, 0, "");

        }


        /// <summary>
        /// 返回上传路径
        /// </summary>
        /// <param name="serverPath">服务器地址</param>
        /// <param name="fileName">文件名称</param>
        /// <returns></returns>
        public static string GetUploadPath(string fileName,int albumid,int userId)
        {
            return GetUploadPath(fileName,albumid, userId,0, 0, "");
        }


        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="file">文件</param>
        /// <param name="limitSize">限制大小</param>
        /// <param name="limitExtensions">文件格式限制</param>
        /// <param name="watermarkPath">水印路径</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <param name="fileName">文件名</param>
        /// <param name="fileName">用户id</param>
        /// <param name="fileName">相册id</param>
        /// <returns></returns>
        public static Common.FileUploadHelper.FileUploadResult FileUpload(HttpPostedFileBase file,int albumid,int userId, int limitSize, string[] limitExtensions, string watermarkPath, out int width, out int height, out string fileName)
        {
            fileName = GetFileName(file.InputStream) + Path.GetExtension(file.FileName);
            string path = GetUploadPath(fileName, albumid, userId);
            return Common.FileUploadHelper.FileUpload(file, path, limitSize, limitExtensions, watermarkPath, out width, out height);
        }

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <param name="limitSize"></param>
        /// <param name="limitExtensions"></param>
        /// <param name="watermarkPath"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static Common.FileUploadHelper.FileUploadResult FileUploads(HttpPostedFile file, int albumid, int userId, int limitSize, string[] limitExtensions, string watermarkPath, out int width, out int height, out string fileName)
        {
            fileName = GetFileName(file.InputStream) + Path.GetExtension(file.FileName);
            string path = GetUploadPath(fileName, albumid, userId);
            return Common.FileUploadHelper.FileUploads(file, path, limitSize, limitExtensions, watermarkPath, out width, out height);
        }


        /// <summary>
        ///生成缩略图
        /// </summary>
        /// <param name="originalImageName">图片名称</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <param name="model">缩略模式</param>
        public static void MakeThumNail(string originalImageName, int width, int height, int albumid, int userId)
        {
            string originalImagePath = GetUploadPath(originalImageName, albumid,  userId);
            string thumNailPath = GetUploadPath(originalImageName, width, height);
            Common.FileUploadHelper.MakeThumNail(originalImagePath, thumNailPath, width, height, thumbModel);

        }


        /// <summary>
        /// 生成所有缩略图
        /// </summary>
        /// <param name="originalImageName">原图片文件名(md5验证码)</param>
        /// <param name="model">生成模式</param>
        public static void MakeThumNail(string originalImageName, int albumid, int userId)
        {
            int width; int height;
            string originalImagePath = GetUploadPath(originalImageName, albumid,  userId);
            string thumNailPath;
            string[] array = System.Enum.GetNames(typeof(SYH.Enum.ThumbImageSize));
            string[] sizearray;
            foreach (string item in array)
            {
                sizearray = item.TrimStart("缩略图".ToCharArray()).Split('x');
                width = Convert.ToInt32(sizearray[0]);
                height = Convert.ToInt32(sizearray[1]);
                thumNailPath = GetUploadPath(originalImageName, width, height);
                Common.FileUploadHelper.MakeThumNail(originalImagePath, thumNailPath, width, height, thumbModel);

            }

        }

        /// <summary>
        /// 获取指定缩略图的大小
        /// </summary>
        /// <param name="ThumbSize"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public static void GetSize(SYH.Enum.ThumbImageSize ThumbSize, out int width, out int height)
        {
            string str = ThumbSize.ToString().TrimStart("缩略图".ToCharArray());
            string[] array = str.Split('x');
            width = Convert.ToInt32(array[0]);
            height = Convert.ToInt32(array[1]);
        }

        #region 临时图片处理


        public static void MakeTempThumNail(string originalImageName, int albumid, int userId)
        {
            int width; int height;
            string originalImagePath = GetTempUploadPath(originalImageName, albumid,  userId);
            string thumNailPath;
            string[] array = System.Enum.GetNames(typeof(SYH.Enum.ThumbImageSize));
            string[] sizearray;
            foreach (string item in array)
            {
                sizearray = item.TrimStart("缩略图".ToCharArray()).Split('x');
                width = Convert.ToInt32(sizearray[0]);
                height = Convert.ToInt32(sizearray[1]);
                thumNailPath = GetTempUploadPath(originalImageName, width, height);
                Common.FileUploadHelper.MakeThumNail(originalImagePath, thumNailPath, width, height, thumbModel);

            }

        }

        /// <summary>
        /// 获取缩略图存放地址
        /// </summary>
        /// <param name="originalImageName"></param>
        /// <param name="type">类型(临时图片,图片)</param>
        /// <returns></returns>
        private static string[] GetThumPath(string originalImageName, string type, int albumid, int userId)
        {
            int width; int height;
            string originalImagePath = GetTempUploadPath(originalImageName, albumid,  userId);
            string thumNailPath;
            string[] array = System.Enum.GetNames(typeof(SYH.Enum.ThumbImageSize));
            string[] sizearray;
            List<string> list = new List<string>();
            foreach (string item in array)
            {
                sizearray = item.TrimStart("缩略图".ToCharArray()).Split('x');
                width = Convert.ToInt32(sizearray[0]);
                height = Convert.ToInt32(sizearray[1]);
                thumNailPath = GetUploadPath(originalImageName, albumid,  userId, width, height, type);
                list.Add(thumNailPath);
            }
            return list.ToArray();
        }


        /// <summary>
        /// 获取图片上传路径
        /// </summary>
        /// <param name="serverPath">服务器地址</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        private static string GetTempUploadPath(string fileName,int albumid, int userId, int width, int height)
        {
            return GetUploadPath(fileName, albumid, userId,width, height, "temp");
        }

        /// <summary>
        /// 获取临时文件缩略图目录
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static string GetTempUploadPath(string fileName, int albumid, int userId)
        {
            return GetUploadPath(fileName, albumid,  userId, 0, 0, "temp");

        }
        /// <summary>
        /// 上传临时文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="limitSize"></param>
        /// <param name="limitExtensions"></param>
        /// <param name="watermarkPath"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static Common.FileUploadHelper.FileUploadResult UploadTempImage(HttpPostedFileBase file,int albumid, int userId, int limitSize, string[] limitExtensions, string watermarkPath, out int width, out int height, out string fileName)
        {
            fileName = GetFileName(file.InputStream) + Path.GetExtension(file.FileName);
            string path = GetTempUploadPath(fileName, albumid,  userId);
            return Common.FileUploadHelper.FileUpload(file, path, limitSize, limitExtensions, watermarkPath, out width, out height);
        }

        /// <summary>
        /// 将缩略图文件发送到图片服务器
        /// </summary>
        /// <param name="originalImageName">文件名称</param>
        public static void MoveTempImage(string originalImageName, int albumid, int userId)
        {
            string[] tempPathArray = GetThumPath(originalImageName, "temp", albumid,  userId);
            string[] imagePath = GetThumPath(originalImageName, "", albumid,  userId);
            for (int i = 0; i < tempPathArray.Length; i++)
            {
                File.Copy(tempPathArray[i], imagePath[i]);
                File.Delete(tempPathArray[i]);
            }
        }

        #endregion
    }
}
